class ApplicationController < ActionController::Base
  protect_from_forgery

  CREATE  = 1
  APPROVE = 2
  EDIT    = 3
  DELETE  = 4

private
  def logged_in?
    current_user ? true : false
  end

  def current_user
    if session[:user_id] && 
       session[:user_ip] = request.remote_ip && 
       User.exists?(session[:user_id])

      @current_user = User.find(session[:user_id])
    else
      @current_user = nil
    end
  end

  def require_login
    unless logged_in?
      flash[:error] = "Must be logged in to perform requested action"
      redirect_to login_users_url
    end
  end

  def require_admin_privs
    unless logged_in? && current_user.administrator
      flash[:error] = "Must have administrative priviledges to perform requested action"
      retirect_to :back
    end
  end

  # Deprecated: Use User.authorize
  def check_permissions(user, event, operation)
    if user.nil? || (event.nil? && !user.administrator) || !user.validated
      return false
    end

    if user.administrator
      return true
    end

    working_on_self = (user.id == event.owner_id)

    if (operation == EDIT    && ((working_on_self && user.right.self_edit)    || (!working_on_self && user.right.other_edit    ))) ||
       (operation == APPROVE && ((working_on_self && user.right.self_approve) || (!working_on_self && user.right.other_approve ))) ||
       (operation == DELETE  && ((working_on_self && user.right.self_delete)  || (!working_on_self && user.right.other_delete  ))) ||
       (operation == CREATE  && ((working_on_self && user.right.self_create)  || (!working_on_self && user.right.other_create  ))) 

      return true
    else
      return false
    end
  end
end
